package cn.ondraw.ragflow.service.impl;

import cn.hutool.json.JSONUtil;
import cn.ondraw.ragflow.pojo.request.*;
import cn.ondraw.ragflow.pojo.response.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import cn.ondraw.ragflow.pojo.request.*;
import cn.ondraw.ragflow.pojo.response.*;
import cn.ondraw.ragflow.pojo.request.*;
import cn.ondraw.ragflow.pojo.response.*;
import cn.ondraw.ragflow.service.DocumentService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
@Slf4j
@RequiredArgsConstructor
public class DocumentServiceImpl implements DocumentService {

    private final PythonApiCaller pythonApiCaller;

    private final String URL_PREFIX = "/api/v1/datasets";

    /**
     * 上传文档到指定数据集
     *
     * @param datasetId 数据集 ID
     * @param files     要上传的文件数组
     * @return 上传文档的响应对象
     */
    @Override
    public UploadDocumentsResponse uploadDocuments(String datasetId, MultipartFile[] files) {
        String url = String.format("%s/%s/documents", URL_PREFIX, datasetId);
        ResponseEntity<?> response = pythonApiCaller.callPostApiWithFiles(url, files);
        return JSONUtil.toBean(response.getBody() != null ? response.getBody().toString() : null, UploadDocumentsResponse.class, true);
    }

    /**
     * 更新指定数据集中的文档信息
     *
     * @param datasetId  数据集 ID
     * @param documentId 文档 ID
     * @param request    更新文档的请求对象
     * @return 更新文档的响应对象
     */
    @Override
    public UpdateDocumentResponse updateDocument(String datasetId, String documentId, UpdateDocumentRequest request) {
        String url = String.format("%s/%s/documents/%s", URL_PREFIX, datasetId, documentId);
        ResponseEntity<?> response = pythonApiCaller.callPutApi(url, request);
        return JSONUtil.toBean(response.getBody() != null ? response.getBody().toString() : null, UpdateDocumentResponse.class, true);
    }

    /**
     * 下载指定数据集中的文档
     *
     * @param datasetId  数据集 ID
     * @param documentId 文档 ID
     * @return 包含文件流的 ResponseEntity 对象
     */
    @Override
    public ResponseEntity<byte[]> downloadDocument(String datasetId, String documentId) {
        String url = String.format("%s/%s/documents/%s", URL_PREFIX, datasetId, documentId);
        return pythonApiCaller.callGetApiForFile(url);
    }

    /**
     * 列出指定数据集中的文档列表
     *
     * @param request 列出文档的请求对象
     * @return 列出文档的响应对象
     */
    @Override
    public ListDocumentsResponse listDocuments(ListDocumentsRequest request) {
        String url = String.format("%s/%s/documents?page=%d&page_size=%d&orderby=%s&desc=%b", URL_PREFIX, request.getDataset_id(), request.getPage(), request.getPage_size(), request.getOrderby(), request.getDesc());
        if (request.getKeywords() != null) {
            try {
                url += "&keywords=" + URLEncoder.encode(request.getKeywords(), StandardCharsets.UTF_8);
            } catch (Exception e) {
                log.error("keywords关键字处理出错 {}", e.getMessage());
            }
        }
        if (request.getId() != null) {
            url += "&id=" + request.getId();
        }
        if (request.getName() != null) {
            try {
                url += "&name=" + URLEncoder.encode(request.getName(), StandardCharsets.UTF_8);
            } catch (Exception e) {
                log.error("name关键字处理出错 {}", e.getMessage());
            }
        }
        ResponseEntity<?> response = pythonApiCaller.callGetApi(url);
        return JSONUtil.toBean(response.getBody() != null ? response.getBody().toString() : null, ListDocumentsResponse.class, true);
    }

    /**
     * 删除指定数据集中的文档
     *
     * @param datasetId 数据集 ID
     * @param request   删除文档的请求对象
     * @return 删除文档的响应对象
     */
    @Override
    public DeleteDocumentsResponse deleteDocuments(String datasetId, DeleteDocumentsRequest request) {
        String url = String.format("%s/%s/documents", URL_PREFIX, datasetId);
        ResponseEntity<?> response = pythonApiCaller.callDeleteApi(url, request);
        return JSONUtil.toBean(response.getBody() != null ? response.getBody().toString() : null, DeleteDocumentsResponse.class, true);
    }

    /**
     * 解析指定数据集中的文档
     *
     * @param datasetId 数据集 ID
     * @param request   解析文档的请求对象
     * @return 解析文档的响应对象
     */
    @Override
    public ParseDocumentsResponse parseDocuments(String datasetId, ParseDocumentsRequest request) {
        String url = String.format("%s/%s/chunks", URL_PREFIX, datasetId);
        ResponseEntity<?> response = pythonApiCaller.callPostApi(url, request);
        return JSONUtil.toBean(response.getBody() != null ? response.getBody().toString() : null, ParseDocumentsResponse.class, true);
    }

    /**
     * 停止解析指定数据集中的文档
     *
     * @param datasetId 数据集 ID
     * @param request   停止解析文档的请求对象
     * @return 停止解析文档的响应对象
     */
    @Override
    public StopParsingDocumentsResponse stopParsingDocuments(String datasetId, StopParsingDocumentsRequest request) {
        String url = String.format("%s/%s/chunks", URL_PREFIX, datasetId);
        ResponseEntity<?> response = pythonApiCaller.callDeleteApi(url, request);
        return JSONUtil.toBean(response.getBody() != null ? response.getBody().toString() : null, StopParsingDocumentsResponse.class, true);
    }
}
